﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRegimenMonitor.Web.Code;
using WaterRegimenMonitor.Web.Models.Common;
using WaterRegimenMonitor.Web.Domain;
using WaterRegimenMonitor.Web.Models.Organization;
using WaterRegimenMonitor.Common;

namespace WaterRegimenMonitor.Web.Controllers
{
    /// <summary>
    /// 组织结构信息控制器
    /// </summary>
    /// <remarks></remarks>
    public class OrganizationController : Controller
    {
        /// <summary>
        /// 返回参照数据。
        /// </summary>
        /// <param name="includeEmpty">是否包含空白项目。</param>
        /// <returns></returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Reference(bool? includeEmpty)
        {
            //查询数据
            var data = OrganizationHelper.GetOrganizationList().OrderBy(item => item.Organization_Code).Select(item => new OrganizationReference()
            {
                Name = item.Organization_Code + " " + item.Organization_Name,
                ID = item.Organization_ID
            }).ToList<OrganizationReference>();

            //判断是否包含空白
            if (includeEmpty.HasValue && includeEmpty.Value)
            {
                //添加空白项目
                data.Insert(0, OrganizationReference.Empty);
            }

            //返回结果
            return Json(new JsonResultViewModel { data = data, success = true }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询组织结构列表
        /// </summary>
        /// <returns>
        /// 查询的工程项目信息列表
        /// </returns>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Select()
        {
            var data = OrganizationHelper.QueryOrganizationTree();
            return Json(new JsonResultViewModel { success = true, message = "组织结构信息加载成功！", data = data },
                        JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 检索指定编号的组织结构。
        /// </summary>
        /// <param name="id">组织结构的编号。</param>
        /// <returns>组织结构信息。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Details(Guid id)
        {
            var organization = OrganizationHelper.GetOrganizationByID(id);
            if (organization == null)
                return Json(new JsonResultViewModel { success = false, message = "查找不到此组织结构信息！", data = null },
                            JsonRequestBehavior.AllowGet);

            return Json(new JsonResultViewModel
            {
                success = true,
                data = new TreeNodeData()
                {
                    id = organization.Organization_ID,
                    parentID = organization.ParentID,
                    name = organization.Organization_Name,
                    code = organization.Organization_Code,
                    leaf = organization.IsLeaf
                }
            },
            JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除组织结构
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Delete(TreeNodeData data)
        {
            var organization = OrganizationHelper.GetOrganizationByID(data.id);

            if (organization == null)
                return Json(new JsonResultViewModel { success = false, message = "没有此组织结构信息！", data = null },
                            JsonRequestBehavior.AllowGet);
            if (!organization.IsLeaf)
                return Json(new JsonResultViewModel { success = false, message = "此组织结构含有子组织结构信息，不可删除，请先删除其包含的组织结构信息！", data = null },
                            JsonRequestBehavior.AllowGet);

            if (OrganizationHelper.DeleteOrganization(data.id) == DeleteResult.UsingError)
            {
                return Json(new JsonResultViewModel { success = false, message = "组织结构删除失败，其它数据正在使用此组织结构！" }, JsonRequestBehavior.AllowGet);
            }

            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "组织结构删除成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新组织结构
        /// </summary>
        /// <param name="data">要更新的组织结构信息。</param>
        /// <returns></returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Update(TreeNodeData data)
        {
            //清除缓存
            HttpContext.Cache.Remove(OrganizationHelper.ORGANIZATION_CACHE_KEY);

            var organization = OrganizationHelper.GetOrganizationByName(data.name);
            if (organization != null && organization.Organization_ID != data.id)
                return Json(new JsonResultViewModel { success = false, message = "已有同名组织结构信息，请更换组织结构名称！", data = null },
                            JsonRequestBehavior.AllowGet);

            organization = OrganizationHelper.GetOrganizationByCode(data.code);
            if (organization != null && organization.Organization_ID != data.id)
                return Json(new JsonResultViewModel { success = false, message = "已有同编号组织结构信息，请更换组织结构编号！", data = null },
                            JsonRequestBehavior.AllowGet);

            OrganizationHelper.UpdateOrganization(data);

            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "更新组织结构信息成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 创建组织结构
        /// </summary>
        /// <returns>执行结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Create(TreeNodeData data)
        {
            //清除缓存
            HttpContext.Cache.Remove(OrganizationHelper.ORGANIZATION_CACHE_KEY);

            var organization = OrganizationHelper.GetOrganizationByName(data.name);
            if (organization != null)
                return Json(new JsonResultViewModel { success = false, message = "已有同名组织结构信息，请更换组织结构名称！", data = null },
                            JsonRequestBehavior.AllowGet);

            organization = OrganizationHelper.GetOrganizationByCode(data.code);
            if (organization != null)
                return Json(new JsonResultViewModel { success = false, message = "已有同编号组织结构信息，请更换组织结构编号！", data = null },
                            JsonRequestBehavior.AllowGet);


            OrganizationHelper.CreateOrganization(data);

            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "添加组织结构信息成功！" }, JsonRequestBehavior.AllowGet);
        }
    }
}
